<template>
	<!--index.wxml-->

	<view class="container">
		<view class="swiper-box">
			<view class="nickname-box">
				<view class="nickname">{{userInfo.nickname}}!你好</view>
			</view>
			<image src="/static/images/bg@2x.png" class="backimg"></image>

			<swiper class="swiper" :indicator-dots="indicatorDots" :autoplay="autoplay" :interval="interval"
				:duration="duration">
				<block v-for="(item, index) in background" :key="index">
					<swiper-item>
						<image class="img" :src="item.adv_img"></image>
					</swiper-item>
				</block>
			</swiper>

		</view>
		<view class="progress-item">
			<view>您目前还可以预支付{{num-ordernum}}次</view>
			<i-progress :percent="percent" :status="status"></i-progress>
		</view>

		<view class="btn-box">
			<view v-if="device==''">未定位到设备</view>
			<view v-else>
				<view>当前设备：{{device.address}}。</view>
				<view>设备编号：{{device.device_num}}</view>
			</view>
			<button style="width: 320px;" class="btn" v-if="login_check==0" @tap="openPopup">授权登录</button>
			<!-- <button style="width: 320px;" class="btn" v-if="login_check==0" open-type="getUserInfo" @getuserinfo="bindGetUserInfo">授权登录</button> -->
			<button style="width: 320px;" class="btn" v-if="login_check==1" @tap="get_paper">立即出纸</button>
			<!-- <button style="width: 320px;" class="btn" @tap="test">测试</button> -->
		</view>
		
		<!-- 登录弹窗 -->
		<ns-login ref="login" @loginSuccess="loginSuccess"></ns-login>
	</view>
</template>

<script>
	//index.js
	const app = getApp().globalData;
	const {
		$Message
	} = require("../../dist/base/index");
	var sotk = null;
	var socketOpen = false;
	// var wsbasePath = "ws://39.105.123.96:39100";
	var wsbasePath = "wss://yhz.axu9.com/wss";
	import iTabBar from "../../dist/tab-bar/index";
	import iTabBarItem from "../../dist/tab-bar-item/index";
	import iProgress from "../../dist/progress/index";
	import iButton from "../../dist/button/index";
	import iModal from "../../dist/modal/index";
	import nsLogin from "../../components/ns-login/ns-login.vue"
	import auth from 'common/js/auth.js';

	export default {
		data() {
			return {
				background: ["/static/images/agent_img01599810087.jpeg", "/static/images/idimg01599807828.jpeg",
					"/static/images/idimg11599810002.jpeg"
				],
				indicatorDots: true,
				vertical: false,
				autoplay: true,
				interval: 2000,
				duration: 500,
				percent: 0,
				status: 'normal',
				canIUse: uni.canIUse('button.open-type.getUserInfo'),
				login_check: 0,
				device: "",
				user: "",
				num: "",
				price: "",
				ordernum: "",
				orderlist: "",
				userInfo: {},
				photo: '',
				user_id: '',
				// nickName: ''
			};
		},

		components: {
			iTabBar,
			iTabBarItem,
			iProgress,
			iButton,
			iModal,
			nsLogin
		},
		watch: {
		 // userInfo(newValue,oldValue){
		 //  console.log(newValue,'watch')
		 //  this.userInfo = newValue
		 // }
		 nickName(newValue,oldValue){
		  console.log(newValue,'watch')
		  // this.nickName = newValue
		 }
		},
		props: {},
		onShow() {
			var _this = this;
			_this.userInfo = uni.getStorageSync('userInfo')
			// _this.nickName = uni.getStorageSync('userInfo') ? uni.getStorageSync('userInfo').nickname : ''
			_this.login_check = uni.getStorageSync('login_check')
			// _this.photo = uni.getStorageSync('userInfo') ? uni.getStorageSync('userInfo').photo : ''
			console.log(_this.nickName,'_this.nickName')
			_this.user_id = uni.getStorageSync('userInfo') ? uni.getStorageSync('userInfo').user_id : ''
			if(_this.user_id != ''){
				_this.getorder(_this.user_id);
			}
			
			
		},
		onLoad: function(query) {
			console.log(app.post_url,'app.post_url')
			var _this = this;
			// _this.userInfo = uni.getStorageSync('userInfo')
			// _this.login_check = uni.getStorageSync('login_check')
			const scene = decodeURIComponent(query.scene);
			console.log(scene, 'scene')
			if (scene === 'undefined') {
				console.log('没有设备号')
				this.setData({
					device: ''
				});
				// this.getorder(this.user_id);
			} else {
				console.log(scene);
				this.get_device(scene);
				// this.getorder(this.user_id);
			} // 登录
			console.log(this.$refs.login, 'login')
			this.getbanner();
		},
		methods: {
			test(){
				uni.navigateTo({
					url: '/pages/test/test'
				})
			},
			getAuthCode() {
				let _this = this
				my.getAuthCode({
					scopes: 'auth_user',
					success: res => {
						const authCode = res.authCode;
						console.log(authCode, 'authCode')
						uni.request({
							url: app.post_url + '/api/wechat/aligettoken',
							//仅为示例，并非真实的接口地址
							dataType: 'text',
							data: {
								code:authCode
							},
							// header: {
							// 	'content-type': 'json'
							// },
							method: 'post',
							success(res) {
								console.log(res, 'aligettoken');
								let aa = res.data
								let jsonString = aa.replace(/﻿/g, '');
								console.log(JSON.parse(jsonString), '1111');
								// JSON.parse(aa)
						
							},
							fail(res) {
								console.log(res, 'fail1111');
							}
							})
					},
					fail: err => {
						console.log('my.getAuthCode 调用失败', err)
					}
				});
			},
			onChooseAvatar() {
				console.log('qqqqqq')
				uni.chooseImage({
					count: 6,
					sizeType: ['original', 'compressed'],
					sourceType: ['album'],
					success: function(res) {
						// 预览图片
						let _this = this
						console.log(res,'res')
						// const { avatarUrl } = e.detail 
						// this.setData({
						//   avatarUrl,
						// })
						let avatarUrl = res.tempFilePaths[0]
						// console.log(_this.avatarUrl, '_this.avatarUrl')
									
						uni.uploadFile({
							url: 'https://yhzzf.axu9.com/api/v1.order/file',
							filePath: avatarUrl,
							name: 'file', //文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容
							header: {
								// "Authorization": uni.getStorageSync('token')
							},
							success: (res) => {
								// let infoObj = JSON.parse(res.data)
								console.log(JSON.parse(res.data), '成功')
								// _this.avatar_url = infoObj.data.img
								// console.log(_this.avatar_url, '_this.avatar_url')
							},
							fail: (err) => {
								console.log(err, '失败')
							}
						})
					}
					});
			
			
			},
			loginSuccess(){
				console.log('11111')
				this.userInfo = uni.getStorageSync('userInfo')
				this.user_id = uni.getStorageSync('userInfo') ? uni.getStorageSync('userInfo').user_id : ''
				this.login_check = uni.getStorageSync('login_check')
				this.getorder(this.user_id);
				// this.photo = uni.getStorageSync('userInfo') ? uni.getStorageSync('userInfo').photo : ''
				
			},
			openPopup() {
				// #ifdef MP-WEIXIN
				this.$refs.login.open()
				// #endif
				// #ifdef MP-ALIPAY
				console.log('支付宝环境')
				this.getAuthCode()
				// #endif
				
			},
			bindGetUserInfo(e) {
				var data = {
					nickname: e.detail.userInfo.nickName,
					photo: e.detail.userInfo.avatarUrl,
					openid: app.openid,
					sex: e.detail.userInfo.gender
				};
				this.reguser(data);
				console.log(e.detail.userInfo);
				console.log(app.openid);
			},
			//获取轮播图及预支付次数
			getbanner: function() {
				var _this = this;

				uni.request({
					url: app.post_url + '/api/v1/banner',
					// data: {},
					// dataType: 'json',
					//仅为示例，并非真实的接口地址
					data:{},
					header:{
						'content-type': 'application/json'
					},
					method: 'post',
					success(res) {
						console.log(res, '获取轮播图及预支付次数');
						_this.background = res.data.data.list
						_this.num = res.data.data.num
						_this.price = res.data.data.price
					},
					fail(res) {
						console.log(res,'fail')
					}

				});
			},
			//获取设备信息
			get_device: function(num) {
				var _this = this;

				uni.request({
					url: app.post_url + '/api/v1/get_device',
					//仅为示例，并非真实的接口地址
					method: 'post',
					data: {
						device_only: num
					},
					success(res) {
						console.log(res);

						// _this.setData({
						// 	device: res.data.data
						// });
						if(res.data.state == 0){
							uni.showToast({
								title: '设备维护中',
								icon: 'error'
							})
							return
						}
						_this.device = res.data.data

						_this.webSocketStart();
					}

				});
			},

			handleAdd() {
				console.log('handleAdd')
				if (this.percent === 100) return;
				this.setData({
					percent: this.percent + 100 / this.num
				});

				if (this.percent === 100) {
					this.setData({
						status: 'success'
					});
				}
			},

			handleReduce() {
				if (this.percent === 0) return;
				this.setData({
					percent: this.percent - 20,
					status: 'normal'
				});
			},

			handleChange({
				detail
			}) {
				console.log(detail);
			},

			//获取订单信息
			getorder: function(user_id) {
				var _this = this;
				// let user_id = uni.getStorageSync('userInfo') ?uni.getStorageSync('userInfo').user_id : ''
				// console.log(user_id);
				uni.request({
					url: app.post_url + '/api/v1/select_order',
					//仅为示例，并非真实的接口地址
					data: {
						user_id: _this.user_id,
						status: 0
					},
					method: 'post',

					success(res) {
						console.log(res, res.data.data.data.length, '获取订单信息');

						_this.setData({
							ordernum: res.data.data.data.length,
							orderlist: res.data.data.data,
							percent: res.data.data.data.length * 20
						});
					}

				});
			},
			get_paper: function() {
				var _this = this;

				console.log(this.device);
				if (!this.device) {
					wx.showToast({
						title: '未找到设备',
						icon: 'none',
						duration: 2000
					})
					return;
				}
				console.log(this.percent, 'this.percent')
				// (this.percent >= 100
				if (this.percent >= 100) {
					uni.showModal({
						title: '需要支付' + this.num * this.price + '元',
						content: '目前已使用' + this.num + '次，结清可再次使用',
						showCancel: false,
						confirmColor: '#459377',

						success(res) {
							if (res.confirm) {
								_this.pay_all()
							}
						}

					});
				} else {
					
					let data = {
						total_price: this.price,
						user_id: this.user_id,
						device_id: this.device.device_id,
						address: this.device.address
					};
					console.log(1);

					if (socketOpen) {
						console.log('socketOpen == true')
						console.log(this.device.device_num, 'device.device_num')
						
						// this.sendSocketMessage({
						// 	device_num: _this.device.device_num,
						// 	msg: 'aa552021081900201\r\n'
						// });
						this.sendSocketMessage({
							id: _this.device.device_num,
							command: 'aa552021081900201\r\n'
						});
					} else {
						console.log('socketOpen == false')
						_this.webSocketReStart();
					} 
					
					// this.add_order(data)

				}
			},
			pay_all: function () {
			  var _this = this;
			  console.log(app,'app1')
			  let user_id = uni.getStorageSync('userInfo') ?uni.getStorageSync('userInfo').user_id : ''
			  uni.request({
			    url: 'https://yhzzf.axu9.com/api/v1.order/pay',
			    //仅为示例，并非真实的接口地址
			    data: {
			      user_id: user_id,
			      status: 0
			    },
			    method: 'post',
			
			    success(res) {
			      console.log(res);
			      uni.requestPayment({
			        timeStamp: res.data.data.payInfo.timeStamp,
			        nonceStr: res.data.data.payInfo.nonceStr,
			        package: res.data.data.payInfo.package,
			        signType: 'MD5',
			        paySign: res.data.data.payInfo.paySign,
			
			        success(res) {},
			
			        fail(res) {}
			
			      });
			    }
			  });
			},
			add_order: function(data) {
				uni.showLoading({
					title: '加载中'
				});

				var _this = this;

				uni.request({
					url: app.post_url + '/api/v1/unifiedorder',
					//仅为示例，并非真实的接口地址
					data: data,
					method: 'post',

					success(res) {
						console.log(res);

						_this.getorder(_this.user_id);

						uni.hideLoading();
					}

				});
			},
			reguser: function(data) {
				var _this = this;

				uni.request({
					url: app.post_url + '/api/v1/userReg',
					//仅为示例，并非真实的接口地址
					data: data,
					method: 'post',

					success(res) {
						console.log(res);

						_this.setData({
							login_check: 1
						});

						getApp().user_info = res.data.data;

						_this.setData({
							user: app.user_info
						});
					}

				});
			},
			//重新连接---------------------------------------------------------------
			webSocketReStart: function(e) {
				var _this = this;

				sotk = uni.connectSocket({
					url: wsbasePath,
					header: {
						'content-type': 'application/json'
					},
					method: "POST",
					success: res => {
						console.log('小程序连接成功：', res);
					},
					fail: err => {
						console.log('出现错误啦！！' + err);
						uni.showToast({
							title: '网络异常！'
						});
					}
				});
				this.webSokcketReMethods();
			},
			//重新
			webSokcketReMethods: function(e) {
				let that = this;
				sotk.onOpen(res => {
					socketOpen = true;
					console.log('监听 WebSocket 连接打开事件11。', res);

					// that.sendSocketMessage({
					// 	device_num: that.device.device_num,
					// 	msg: 'aa552021081900201\r\n'
					// });
					that.sendSocketMessage({
						id: that.device.device_num,
						command: 'aa552021081900201\r\n'
					});
				});
				sotk.onClose(onClose => {
					console.log('监听 WebSocket 连接关闭事件。', onClose);
					socketOpen = false;
					// if (onClose.code === 1006) {
					//       console.error('连接已关闭，无法建立连接1');
					//       // 尝试重新连接
					//       setTimeout(that.webSocketReStart, 5000);
					//     } else {
					//       console.log('onClose.code', code, '原因1：', reason);
					//     }
				});
				sotk.onError(onError => {
					console.log('监听 WebSocket 错误。错误信息', onError);
					socketOpen = false;
				});
				sotk.onMessage(onMessage => {
					console.log(onMessage.data,'jsjsjsjsjsjsj');
					var data1 = JSON.parse(onMessage.data);
					if(data1.code == 1){
						let data = {
							total_price: this.price,
							user_id: this.user_id,
							device_id: this.device.device_id,
							address: this.device.address
						};
						this.add_order(data)
					}else {
						uni.showToast({
							title: data1.msg,
							icon: 'error'
						})
					}
					that.closeWebsocket(onMessage.data); //var data = JSON.parse(onMessage.data);
					//console.log('监听WebSocket接受到服务器的消息事件。服务器返回的消息',data);
				});
			},
			//开始webSocket---------------------------------------------------------------
			webSocketStart: function(e) {
				var _this = this;

				sotk = uni.connectSocket({
					url: wsbasePath,
					header: {
						'content-type': 'application/x-www-form-urlencoded'
					},
					method: "POST",
					success: res => {
						console.log('小程序连接成功：', res);
					},
					fail: err => {
						console.log('出现错误啦！！' + err);
						uni.showToast({
							title: '网络异常！'
						});
					}
				});
				this.webSokcketMethods();
			},
			//监听指令
			webSokcketMethods: function(e) {
				let that = this;
				sotk.onOpen(res => {
					socketOpen = true;
					console.log('监听 WebSocket 连接打开事件。', res);
					console.log(that.device.device_num,'this.device.device_num')
					// that.sendSocketMessage({
					// 	device_num: that.device.device_num,
					// 	msg: 'aa552021081900201\r\n'
					// });
					// that.sendSocketMessage({
					// 	id: that.device.device_num,
					// 	command: 'aa552021081900201\r\n'
					// });
				});
				sotk.onClose(onClose => {
					console.log('监听 WebSocket 连接关闭事件。1', onClose);
					socketOpen = false;
					// if (onClose.code === 1006) {
					//       console.error('连接已关闭，无法建立连接');
					//       // 尝试重新连接
					//       setTimeout(that.webSocketReStart, 5000);
					//     } else {
					//       console.log('onClose.code', code, '原因：', reason);
					//     }
				});
				sotk.onError(onError => {
					console.log('监听 WebSocket 错误。错误信息', onError);
					socketOpen = false;
				});
				sotk.onMessage(onMessage => {
					console.log(onMessage.data,'ffdddgdfgdfhdfh');
					var data1 = JSON.parse(onMessage.data);
					console.log(data1.code,'bbbbbb')
					if(data1.code == 1){
						console.log('走了么1')
						let data = {
							total_price: this.price,
							user_id: this.user_id,
							device_id: this.device.device_id,
							address: this.device.address
						};
						console.log(data,'datatatatatat223444')
						this.add_order(data)
					}else {
						wx.showToast({
							title: data1.msg,
							icon: 'error'
						})
					}
					that.closeWebsocket(onMessage.data); //var data = JSON.parse(onMessage.data);
					//console.log('监听WebSocket接受到服务器的消息事件。服务器返回的消息',data);
				});
			},
			//发送消息
			sendSocketMessage: function(msg) {
				console.log(11);
				let that = this;

				if (socketOpen) {
					console.log('通过 WebSocket 连接发送数据', JSON.stringify(msg));
					sotk.send({
						data: JSON.stringify(msg)
					}, function(res) {
						console.log('已发送', res);
					});
				}
			},
			//关闭连接
			closeWebsocket: function(str) {
				if (socketOpen) {
					sotk.close({
						code: "1000",
						reason: str,
						success: function() {
							console.log("成功关闭websocket连接");
						}
					});
				}
			}
		}
	};
</script>
<style>
	@import "./index.css";
	.headimg{
	  width:70px;
	  height:70px;
	  border-radius: 20px;
	  margin-right: 15px;
	  box-shadow: 1px 2px 14px #000;
	}
</style>